from django import forms
from django.utils.html import escape
from django.utils.safestring import mark_safe

class SpanWidget(forms.Widget):
    def __init__(self, *args, **kwargs):
        super(SpanWidget, self).__init__(*args, **kwargs)
        self.displayvalue = False
        self.fieldvalue = False
        self.primarykey = False
    
    #set value for choicefields, so it does show string and not index
    def set_value(self, value, actualvalues=None, multi=False):
        self.displayvalue = value
        if multi == True:
            self.fieldvalue = actualvalues
        elif actualvalues != None:
            self.primarykey = actualvalues
    """
    Renders a value wrapped in a <span> tag.
    Based on Killarny, http://www.djangosnippets.org/snippets/1340/
    Modified to place the value in a hidden control, so that it
    returns a value in the GET/POST response.
    """
    def render(self, name, value, attrs=None):
        final_attrs = self.build_attrs(attrs, name=name)
        if value:
            if self.fieldvalue:
                hidden = ""
                for item in self.fieldvalue:
                    hidden += ("<input type='hidden' name='%s' value='%s' />" \
                         % (name, escape(item)))
            elif self.primarykey:
                hidden = "<input type='hidden' name='%s' value='%s' />" \
                         % (name, escape(self.primarykey))
            else:
                hidden = "<input type='hidden' name='%s' value='%s' />" \
                         % (name, escape(value))
        else:
            hidden = ""

        if self.displayvalue:
            display = self.displayvalue
        else:
            display = value

        return mark_safe(u"<span%s >%s</span>%s&nbsp;" % ( 
                forms.util.flatatt(final_attrs),
                display,
                hidden))
                
    def _has_changed(self, initial, data):
        return False